<?php namespace App\Http\Services;

use Requests;
use Requests_Exception;
use Log;

class HaoTing
{
    private $apiKey = '34dfd103960439d08d11829e85615611';
    private $haoTingYunUrl = 'http://sms.haotingyun.com/v2';
    private $haoTingYunSmsUrl = '/sms/single_send.json';

    public function sendExpressSms($sendTo,$num)
    {
        $result = self::doPost($this->haoTingYunSmsUrl, [
            'apikey'    => $this->apiKey,
            'mobile'    => $sendTo,
            'text'      => '【找我啊】您的验证码是'.$num.',如非本人使用请忽略此短信',
        ]);
        return $result;
    }

    private function doPost($url, array $param)
    {
        $response = null;
        try {
            $response = Requests::get($this->haoTingYunUrl . $url, [
                'Accept'       => 'text/plain;charset=utf-8',
                'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
            ], $param);
        } catch (Requests_Exception $ex) {
            Log::error('Request Error To HaoTingYun:'.$ex);
        }

        var_dump($response);
        if (!$response->success) {
            return false;
        }

        $res = json_decode($response->body);
        if (is_null($res))
            return false;

        return $res;
    }
}
